'''
@file:    color_recognition.py
@company: Hiwonder
@author:  CuZn
@date:    2023-08-21
@description: 学习一种颜色并识别
            #第一步：把你想要跟踪的物体放在盒子里的相机前
            #第二步：确保要跟踪的对象的颜色完全被框包围
            #第三步：按下按键，开始学习
'''


import sensor
import image
import time
import lcd

#载入按键控制模块
from hiwonder import hw_key

#初始化LCD
lcd.init()
#以下是初始化传感器
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time = 100)
sensor.set_auto_gain(False)
sensor.set_auto_whitebal(False)
#帧率时钟
clock = time.clock()

#方框参数
r = [(320//2)-(50//2), (240//2)-(50//2), 50, 50]

#创建按键控制对象
key = hw_key()

state = key.key_scan(1)

#显示图像，等待按键按下
while (state == 0):
    state = key.key_scan(1)
    img = sensor.snapshot()
    img.draw_rectangle(r)
    lcd.display(img)


print("Start learning ...")
threshold = [50, 50, 0, 0, 0, 0] # Middle L, A, B values.

#第一次赋值
img = sensor.snapshot()
hist = img.get_histogram(roi=r)
lo = hist.get_percentile(0.01) #获得直方图在1%范围内的CDF(根据需要调整)!
hi = hist.get_percentile(0.99) #获得直方图在99%范围内的CDF(根据需要调整)!
threshold[0] = (threshold[0] + lo.l_value()) // 2
threshold[1] = (threshold[1] + hi.l_value()) // 2
threshold[2] = (threshold[2] + lo.a_value())
threshold[3] = (threshold[3] + hi.a_value())
threshold[4] = (threshold[4] + lo.b_value())
threshold[5] = (threshold[5] + hi.b_value())



#连续捕捉了50张图像学习阶段
for i in range(50):
    img = sensor.snapshot()
    hist = img.get_histogram(roi=r)
    lo = hist.get_percentile(0.01) #获得直方图在1%范围内的CDF(根据需要调整)!
    hi = hist.get_percentile(0.99) #获得直方图在99%范围内的CDF(根据需要调整)!
    #hi = hist.get_percentile(0.70) #获得直方图在99%范围内的CDF(根据需要调整)!
    #以百分位数表示的平均值
    threshold[0] = (threshold[0] + lo.l_value()) // 2
    threshold[1] = (threshold[1] + hi.l_value()) // 2
    threshold[2] = (threshold[2] + lo.a_value()) // 2
    threshold[3] = (threshold[3] + hi.a_value()) // 2
    threshold[4] = (threshold[4] + lo.b_value()) // 2
    threshold[5] = (threshold[5] + hi.b_value()) // 2
    #将识别区域用方框圈出来
    for blob in img.find_blobs([threshold], pixels_threshold=100, area_threshold=100, merge=True, margin=10):
        img.draw_rectangle(blob.rect())
        img.draw_cross(blob.cx(), blob.cy())
        img.draw_rectangle(r, color=(0,255,0))
    lcd.display(img)
print("threshold:", threshold)


print("Thresholds Learning completed...")

print("Start Color Recognition...")

#loop
while(True):
    #用于计算帧率的函数，这里表示开始计时
    clock.tick()
    #从传感器捕获一张图像
    img = sensor.snapshot()
    #遍历图像中找到的颜色区块
    for blob in img.find_blobs([threshold], pixels_threshold=100, area_threshold=100, merge=True, margin=10):
        #绘制矩形和十字标记
        img.draw_rectangle(blob.rect())
        img.draw_cross(blob.cx(), blob.cy())
    #显示在LCD上
    lcd.display(img)
    #打印帧率
    #print(clock.fps())
